<template>
  <!-- 入库 -->
  <Dialog class="two-columns" title="入库" :visible="visible" :loading="loading" @close="handleClose" @confirm="submitStockForm">
    <el-form ref="requestFromRef" :model="stockInfo" :rules="rules" label-width="58px" class="demo-ruleForm">
      <el-form-item label="仓库：" prop="warehouseId">
        <el-select v-model="stockInfo.warehouseId" filterable placeholder="请选择仓库" style="width: 237.5px" class="el-select-y">
          <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
    </el-form>
    <div class="tx">挑选</div>
    <GetProductContent ref="GetProductContent" :is-commonly-used="true" :warehouse-id="stockInfo.warehouseId" inventory="进货" :tabs-text="categorys" @listChange="listChange" />
    <div class="tx">入库清单</div>
    <el-table :data="goodsList" border :row-class-name="tableColor" max-height="300">
      <el-table-column label="名称" prop="name" :show-overflow-tooltip="true" />
      <el-table-column label="类型" prop="productAttrib" min-width="50px" :show-overflow-tooltip="true" />
      <el-table-column label="规格" prop="spec" min-width="50px" :show-overflow-tooltip="true" />
      <el-table-column label="单位" prop="unit" min-width="50px" :show-overflow-tooltip="true" />
      <el-table-column label="入库数量" min-width="120" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.purchaseCount" controls-position="right" :min="0" style="width: 120px;" />
        </template>
      </el-table-column>
      <el-table-column label="进货单价" min-width="120px" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.price" controls-position="right" style="width: 120px;" :min="0" />
        </template>
      </el-table-column>
      <el-table-column label="批次号" min-width="100px" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-input v-model="scope.row.inventoryBatch" controls-position="right" style="width: 80px;" />
        </template>
      </el-table-column>
      <el-table-column label="生产日期" :show-overflow-tooltip="true" min-width="150">
        <template slot-scope="scope">
          <el-date-picker v-model="scope.row.productionDate" type="date" value-format="timestamp" :picker-options="pickerOptions" placeholder="选择日期" style="width:150px;" />
        </template>
      </el-table-column>
      <el-table-column label="保质期（天）" min-width="120" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.expiredTime" controls-position="right" :min="0" style="width: 120px;" />
        </template>
      </el-table-column>
      <el-table-column label="供货商" min-width="120" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-input v-model="scope.row.inventorySupplier" controls-position="right" style="width: 120px;" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="deleteBtn(scope.row)">删除</el-button>
          <el-button v-if="!scope.row.isAdd" type="text" @click="addBatch(scope)"><i class="el-icon-plus" />批次</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-form ref="requestFromRef" :model="stockInfo" label-width="50px">
      <el-form-item label="备注：" class="remarkStyle">
        <el-input v-model="stockInfo.remark" type="textarea" :rows="2" placeholder="请输入备注" class="textarea-border" />
        <!-- <span>
          <span><strong>备注：</strong></span>
          <el-input v-model="stockInfo.remark" type="textarea" :rows="2" placeholder="请输入内容" class="textarea-border" />
        </span> -->
      </el-form-item>
    </el-form>
  </Dialog>
</template>
<script>
import Dialog from "@/components/Dialog/index";
import { tableColor } from '@/utils/common.js';
import GetProductContent from "@/components/getProductContent";
import { warehouseList } from "@/utils/common";
export default {
  components: {
    Dialog,
    GetProductContent,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      tableColor,
      loading: false,
      warehouseList: [],
      stockInfo: {},
      goodsList: [],
      pickerOptions: {
        disabledDate(time) { // 禁用选择之后的日期
          return time.getTime() > Date.now() - 8.64e7;
        },
      },
      rules: {
        warehouseId: [
          { message: '请选择仓库', trigger: 'change', required: true },
        ],
      },
      categorys: [
        {
          label: "物品",
          name: "物品",
        },
        {
          label: "药品",
          name: "药品",
        },
      ],
    };
  },
  mounted() {
    this.findAllWarehouse();
  },
  methods: {
    handleClose() {
      this.$emit('handleClose');
    },
    async findAllWarehouse() {
      const uesrId = this.$store.getters.currentUserInfo.id;
      this.warehouseList = warehouseList(uesrId);
      console.log(this.warehouseList);
    },
    async submitStockForm() {
      this.$refs['requestFromRef'].validate(async valid => {
        if (!valid) return;
        if (!this.stockInfo.warehouseId) {
          this.$message.error("请选择仓库");
          return;
        }
        for (var i = 0; i < this.warehouseList.length; i++) {
          if (this.stockInfo.warehouseId === this.warehouseList[i].id) {
            this.stockInfo.warehouseName = this.warehouseList[i].name;
          }
        }
        this.stockInfo.handler = this.$store.getters.currentUserInfo.name;
        if (this.goodsList.length === 0) return this.$message.error('入库商品不能为空！');
        let isTrue = true;
        let msg = "";
        this.goodsList.forEach(item => {
          item.materialMedicineId = item.id;
          item.inventoryProducer = item.producerName;
          item.specs = item.spec;
          item.materialMedicineType = item.productAttrib;
          if (isTrue && !msg) {
            if (!item.purchaseCount) {
              isTrue = false;
              msg = "请输入入库数量";
            } else if (!item.price) {
              isTrue = false;
              msg = "请输入进货单价";
            }
          }
        });
        if (!isTrue) {
          this.$message.error(msg);
          return;
        }
        this.loading = true;
        const res = await this.$api['warehouse/stock/stock']({ ...this.stockInfo, purchaseOrderDtoList: this.goodsList });
        this.loading = false;
        this.goodsList = [];
        this.stockInfo = {};
        if (res.code !== 200) return this.$message.error(res.msg);
        this.$message.success('添加进货成功！');
        this.$emit("successHandle");
      });
    },
    // 删除商品
    async deleteBtn(row) {
      const confirmResult = await this.$confirm('请确认是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err) => err);
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除');
      }
      if (row.isAdd) {
        this.goodsList.forEach((item, index) => {
          if (item.id === row.id && item.isAdd) {
            this.goodsList.splice(index, 1);
          }
        });
      } else {
        this.$refs.GetProductContent.deteleContent(row.id);
      }
    },
    listChange(list) {
      const lists = JSON.parse(JSON.stringify(list));
      // 给goodsList添加新增的数据
      lists.forEach(item => {
        let isTrue = false;
        this.goodsList.forEach(json => {
          if (item.id === json.id) {
            isTrue = true;
          }
        });
        if (!isTrue) {
          this.$set(item, 'billNum', item.availableStock === '0' ? 0 : 1);
          this.goodsList.push(item);
        }
      });
      // 删除已取消勾选的数据
      for (let i = 0; i < this.goodsList.length; i++) {
        const item = this.goodsList[i];
        let isTrue = false;
        for (let n = 0; n < lists.length; n++) {
          if (item.id === lists[n].id) {
            isTrue = true;
          }
        }
        if (!isTrue) {
          this.goodsList.splice(i, 1);
          i--;
        }
      }
    },
    addBatch(scope) {
      const index = scope.$index + 1;
      const row = JSON.parse(JSON.stringify(scope.row));
      this.$set(row, 'isAdd', true);
      this.goodsList.splice(index, 0, row);
    },
  },
};
</script>
<style scoped lang='scss'>
.tx {
  margin-bottom: 20px;
  font-weight: bold;
}
.remarkStyle{
  margin-top: 15px;
}
</style>
